package com.example.hello.controller;

import com.example.hello.bean.User1;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class JdbcController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/jdbcinsert")
    @ResponseBody
    public String insert(){
        Date date=new Date();
        int up=jdbcTemplate.update("INSERT into user(username) values(?)",date);
        if (up>0){
            return "success";
        }else{
            return "error";
        }
    }
        @RequestMapping("/jdbcselect")
         @ResponseBody
        public String select(){
            List<Map<String, Object>> ulist=jdbcTemplate.queryForList("select * from user");
         System.out.println(ulist);
            return "ulist";
        }
    @RequestMapping("/jdbcselectone")
    @ResponseBody
    public String selectOne(){
        User1 user1=new User1();
                user1.setUsername("admin");
        List<User1> userList=jdbcTemplate.query("select * from user where username=?", new Object[]{user1.getUsername()},
                new BeanPropertyRowMapper(User1.class));
        System.out.println(userList);
       Map<String,Object> map=new HashMap<>();
       map.put("username",userList.get(0).getUsername());
       map.put("password",userList.get(0).getPassword());
        Gson gson=new Gson();
        return gson.toJson(map);
       }
}
